clear all;

cd ..; cd ..; cd ..;
load('code_main_model\6_implied_w_r\computation_results\data.mat','Z','d','credit','Y');
cd 'code_figure_table\OA\Figure OA12';

ZZ=unique(Z);

% mkt_index1=find(Z==ZZ(1) & d(1,:)==median(d(1,:))); mkt_index1=mkt_index1(1);
mkt_index1=find(Z==ZZ(1) & abs(d(1,:)-median(d(1,:)))<1); mkt_index1=mkt_index1(1);
mkt_index2=find(Z==ZZ(1) & d(1,:)==0); mkt_index2=mkt_index2(1);

credit_ini1=credit(1,mkt_index1);
output_ini1=Y(1,mkt_index1);
credit_new1=credit(1,mkt_index2);
output_new1=Y(1,mkt_index2);

% mkt_index1=find(Z==ZZ(2) & d(1,:)==median(d(1,:))); mkt_index1=mkt_index1(1);
mkt_index1=find(Z==ZZ(2) & abs(d(1,:)-median(d(1,:)))<1); mkt_index1=mkt_index1(1);
mkt_index2=find(Z==ZZ(2) & d(1,:)==0); mkt_index2=mkt_index2(1);

credit_ini2=credit(1,mkt_index1);
output_ini2=Y(1,mkt_index1);
credit_new2=credit(1,mkt_index2);
output_new2=Y(1,mkt_index2);

% mkt_index1=find(Z==ZZ(3) & d(1,:)==median(d(1,:))); mkt_index1=mkt_index1(1);
mkt_index1=find(Z==ZZ(3) & abs(d(1,:)-median(d(1,:)))<1); mkt_index1=mkt_index1(1);
mkt_index2=find(Z==ZZ(3) & d(1,:)==0); mkt_index2=mkt_index2(1);

credit_ini3=credit(1,mkt_index1);
output_ini3=Y(1,mkt_index1);
credit_new3=credit(1,mkt_index2);
output_new3=Y(1,mkt_index2);

% mkt_index1=find(Z==ZZ(4) & d(1,:)==median(d(1,:))); mkt_index1=mkt_index1(1);
mkt_index1=find(Z==ZZ(4) & abs(d(1,:)-median(d(1,:)))<1); mkt_index1=mkt_index1(1);
mkt_index2=find(Z==ZZ(4) & d(1,:)==0); mkt_index2=mkt_index2(1);

credit_ini4=credit(1,mkt_index1);
output_ini4=Y(1,mkt_index1);
credit_new4=credit(1,mkt_index2);
output_new4=Y(1,mkt_index2);

% mkt_index1=find(Z==ZZ(5) & d(1,:)==median(d(1,:))); mkt_index1=mkt_index1(1);
mkt_index1=find(Z==ZZ(5) & abs(d(1,:)-median(d(1,:)))<1); mkt_index1=mkt_index1(1);
mkt_index2=find(Z==ZZ(5) & d(1,:)==0); mkt_index2=mkt_index2(1);

credit_ini5=credit(1,mkt_index1);
output_ini5=Y(1,mkt_index1);
credit_new5=credit(1,mkt_index2);
output_new5=Y(1,mkt_index2);


credit_ini=[credit_ini1,credit_ini2,credit_ini3,credit_ini4,credit_ini5];
credit_new=[credit_new1,credit_new2,credit_new3,credit_new4,credit_new5];
output_ini=[output_ini1,output_ini2,output_ini3,output_ini4,output_ini5];
output_new=[output_new1,output_new2,output_new3,output_new4,output_new5];

pop_den_median=150;

x=ZZ;
y_credit_ini=pop_den_median * credit_ini;
y_credit_new=pop_den_median * credit_new;
y_credit_gap=y_credit_new-y_credit_ini;
y_output_ini=pop_den_median * output_ini;
y_output_new=pop_den_median * output_new;
y_output_gap=y_output_new-y_output_ini;


figure;
plot(x,y_credit_ini);
hold on
plot(x,y_credit_new);
hold on
plot(x,y_credit_gap);

figure;
plot(x,y_output_ini);
hold on
plot(x,y_output_new);
hold on
plot(x,y_output_gap);

save('BE.mat','x','y_credit_ini','y_credit_new','y_credit_gap',...
    'y_output_ini','y_output_new','y_output_gap');